import requests
import os
import zipfile
import sys
import stat


def un_zip(file_name, dst):
    source_file_name = os.path.basename(file_name).split(".")[0]
    dst = os.path.join(dst, source_file_name)
    """解压 zip 文件"""
    zip_file = zipfile.ZipFile(file_name)
    if os.path.isdir(dst):
        pass
    else:
        os.mkdir(dst)
    for names in zip_file.namelist():
        zip_file.extract(names, dst)
    zip_file.close()
    os.chmod(dst, stat.S_IRWXU + stat.S_IXGRP + stat.S_IXOTH)


response = requests.get("https://registry.npmmirror.com/-/binary/chromedriver/")
resJson = response.json()
searchName = sys.argv[1]
searchArr = searchName.split(".")
mcount = 0
strs = set()
for item in resJson:
    driverName = item["name"]
    driverArr = driverName.split(".")
    count = 0
    for i in range(len(driverArr)):
        if len(searchArr) <= i:
            continue
        if searchArr[i] == driverArr[i]:
            count += 1
    if count > mcount:
        mcount = count
        strs = set()
        strs.add(driverName[:-1])
    if count == mcount:
        strs.add(driverName[:-1])
print(strs)
down_url = "https://registry.npmmirror.com/-/binary/chromedriver/{}/chromedriver_linux64.zip".format(
    list(strs)[0]
)
print(down_url)
down_res = requests.get(url=down_url)
folder_name = "/opt/soft/selenium"
file_name = os.path.join(folder_name, "chromedriver_linux64.zip")
if not os.path.exists(folder_name):
    os.makedirs(folder_name)
print(down_res)
with open(file_name, "wb") as code:
    code.write(down_res.content)
    code.flush()
    code.close()
un_zip(file_name, os.path.dirname(file_name))
os.chmod(
    "/opt/soft/selenium/chromedriver_linux64/chromedriver",
    stat.S_IRWXU + stat.S_IXGRP + stat.S_IXOTH,
)
